package se.hrbustrc.hlgshopping.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import se.hrbustrc.hlgshopping.entity.Address;
import se.hrbustrc.hlgshopping.entity.OrderInfo;
import se.hrbustrc.hlgshopping.service.OrderInfoService;
import se.hrbustrc.hlgshopping.utils.Result;
import se.hrbustrc.hlgshopping.utils.UserContext;
import se.hrbustrc.hlgshopping.service.AddressService;
import se.hrbustrc.hlgshopping.vo.OrderVO;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderInfoService orderInfoService;
    
    @Autowired
    AddressService addressService;

    /**
     * 添加订单
     * @param orderRequestVO 订单信息
     * @return 添加结果
     */
    @PostMapping("/add")
    public Result addOrder(@RequestBody se.hrbustrc.hlgshopping.vo.OrderRequestVO orderRequestVO) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            return orderInfoService.addOrder(orderRequestVO, userId);
        } catch (Exception e) {
            return new Result().error("添加订单异常: " + e.getMessage());
        }
    }
    
    /**
     * 删除订单
     * @param orderId 订单ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{orderId}")
    public Result deleteOrder(@PathVariable("orderId") Long orderId) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 验证订单是否属于当前用户
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            if (orderInfo == null) {
                return new Result().error("订单不存在");
            }
            
            if (!orderInfo.getUserid().equals(userId)) {
                return new Result().error("无权限删除该订单");
            }
            
            return orderInfoService.deleteOrder(orderId.intValue());
        } catch (Exception e) {
            return new Result().error("删除订单异常: " + e.getMessage());
        }
    }
    
    /**
     * 修改订单状态
     * @param id 订单ID
     * @param orderState 订单状态
     * @return 修改结果
     */
    @PutMapping("/upState/{id}/{orderState}")
    public Result upOrderState(@PathVariable("id") Long id, 
                                  @PathVariable("orderState") Integer orderState) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 验证订单是否属于当前用户
            OrderInfo orderInfo = orderInfoService.getById(id);
            if (orderInfo == null) {
                return new Result().error("订单不存在");
            }
            
            if (!orderInfo.getUserid().equals(userId)) {
                return new Result().error("无权限修改该订单状态");
            }
            
            return orderInfoService.upOrderState(id, orderState);
        } catch (Exception e) {
            return new Result().error("修改订单状态异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情（包含订单信息和订单明细）
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/detail/{orderId}")
    public Result getOrderDetail(@PathVariable("orderId") Long orderId) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 获取订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            if (orderInfo == null) {
                return new Result().error("订单不存在");
            }
            
            // 验证订单是否属于当前用户
            if (!orderInfo.getUserid().equals(userId)) {
                return new Result().error("无权限查看该订单");
            }
            
            // 获取订单详情（包含订单信息和订单明细）
            OrderVO orderDetail = orderInfoService.getOrderDetail(orderId);
            return new Result().ok(orderDetail);
        } catch (Exception e) {
            return new Result().error("查询订单详情异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情（仅订单信息）
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("/get/{orderId}")
    public Result getOrder(@PathVariable("orderId") Long orderId) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 获取订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            if (orderInfo == null) {
                return new Result().error("订单不存在");
            }
            
            // 验证订单是否属于当前用户
            if (!orderInfo.getUserid().equals(userId)) {
                return new Result().error("无权限查看该订单");
            }
            
            return new Result().ok(orderInfo);
        } catch (Exception e) {
            return new Result().error("查询订单异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户的所有订单
     * @return 订单列表
     */
    @GetMapping("/list")
    public Result getOrderList() {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 查询当前用户的所有订单
            return new Result().ok(
                orderInfoService.lambdaQuery()
                    .eq(OrderInfo::getUserid, userId)
                    .list()
            );
        } catch (Exception e) {
            return new Result().error("查询订单列表异常: " + e.getMessage());
        }
    }
    
    /**
     * 修改订单地址
     * @param orderId 订单ID
     * @param addressId 地址ID
     * @return 修改结果
     */
    @PutMapping("/updateAddress/{orderId}")
    public Result updateOrderAddress(@PathVariable("orderId") Long orderId,
                                        @RequestParam("addressId") Long addressId) {
        try {
            // 从UserContext中获取当前用户ID
            Long userId = UserContext.getUserId();
            if (userId == null) {
                return new Result().error("用户未登录");
            }
            
            // 获取订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            if (orderInfo == null) {
                return new Result().error("订单不存在");
            }
            
            // 验证订单是否属于当前用户
            if (!orderInfo.getUserid().equals(userId)) {
                return new Result().error("无权限修改该订单地址");
            }
            
            // 获取新地址信息
            Address address = addressService.getById(addressId);
            if (address == null) {
                return new Result().error("地址信息不存在");
            }
            
            // 更新订单地址信息
            orderInfo.setReceivercontact(address.getContactor());
            orderInfo.setReceivermobile(address.getPhone());
            orderInfo.setReceiveraddress(address.getAddress());
            orderInfo.setUpdatetime(LocalDateTime.now());
            
            // 保存更新
            boolean updated = orderInfoService.updateById(orderInfo);
            if (updated) {
                return new Result().ok("订单地址修改成功");
            } else {
                return new Result().error("订单地址修改失败");
            }
        } catch (Exception e) {
            return new Result().error("修改订单地址异常: " + e.getMessage());
        }
    }
}
